<?php

namespace App\Http\Middleware;

use App\Models\Server;
use Closure;
use Illuminate\Http\JsonResponse;

class ApiSignature
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $id=$request->get('id');
        $s=$request->get('s');
        $t=$request->get('t');
        $r=$request->get('r');
//        return JsonResponse::create([!is_numeric($id) , !$s , !is_numeric($t) , !$r]);
        if(!is_numeric($id) || !$s || !is_numeric($t) || !$r){
            return JsonResponse::create(['err'=>1,'msg'=>'err param'],404);
        }

        $time=time()-(int)$t;
        if ($time<0 || $time>3000){
            return JsonResponse::create(['err'=>1,'msg'=>'err time','data'=>[
                time(),$t
            ]],404);
        }

        $server=Server::find($id);
        if(!$server){
            return JsonResponse::create(['err'=>1,'msg'=>'err id'],404);
        }
        if(!$server->api_key){
            return JsonResponse::create(['err'=>1,'msg'=>'no server'],404);
        }

        $signature=md5($t.$server->api_key.$r);
        if($s!=$signature){
            return JsonResponse::create(['err'=>1,'msg'=>'err signature','signature'=>$signature],404);
        }

        return $next($request);
    }
}
